<!--  -->
<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :class="{disabled:fileList.length }"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="isShowProgress" :text-inside="true" :stroke-width="26" :percentage="percentage" style="width:146px" />
    <el-dialog title="查看图片" :visible="showDialog" @close="showDialog=false">
      <el-row type="flex" justify="center">
        <img :src="imgUrl" alt="">
      </el-row>

    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDUpwoRovqeIl9OTJthbLtBDyUjqjZ9Wee',
  SecretKey: 'sUq4fBe6OR4bx61g5SfqrdLnyxpulQwE'
})
export default {
  data() {
    return {
      fileList: [

      ],
      showDialog: false,
      imgUrl: '',
      percentage: 0,
      isShowProgress: true
    }
  },
  methods: {
    onPreview(file) {
      console.log(file)
      this.showDialog = true
      this.imgUrl = file.url
    },
    onRemove(file, fileList) {
      // 由于没有双向绑定, 删除图片this.fileList会遗留
      // 这个函数就把最新列表传进来, 覆盖即可
      this.fileList = fileList
    },
    onChange(file, fileList) {
      // 由于没有双向绑定，添加进来的图片也没有添加到fileList
      this.fileList = fileList
    },
    // 上传前的校验
    beforeUpload(file) {
      console.log('上传前的校验', file)
      // 文件大小的校验
      const maxSize = 2 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.warning('文件不能超过2m')
        return false
      }
      // 文件格式的校验
      const whiteList = ['image/jpeg', 'image/png']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('文件只支持jpeg和png格式')
        return false
      }
    },
    httpRequest(params) {
      // 此处替代默认上传行为,即阻止action
      console.log(69, params)
      cos.putObject({
        Bucket: 'hr70-1309020954', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        // 腾讯云上传完毕 element 完全不知道
        // 需要手动进行后续操作
        if (!err) {
          this.fileList[0].status = 'success'
          this.fileList[0].url = 'http://' + data.Location
        }
        setTimeout(() => {
          this.isShowProgress = false
        }, 1000)
      })
    }
  }
}

</script>
<style lang='scss' scoped>
.disabled{
    ::v-deep .el-upload--picture-card{
        display: none
    }
}
</style>
